<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>首页</title>
    <link rel="stylesheet" href="../lib/css/bootstrap.min.css" />
    <script src="../lib/js/jquery-3.3.1.min.js"></script>
    <script src="../lib/js/bootstrap.min.js"></script>
    <script src="../lib/js/thingjs.min-v1.2.2.4.js"></script>
    <script src="../lib/js/thing.widget.min.js"></script>

    <style>
        html, body{
            width: 100%;
            height: 100%;
            margin: 0;
            padding: 0;
            overflow: hidden;
        }
        header{
            position:absolute;
            z-index:99;
            width:100%;
            background-color: white
        }

    </style>
</head>
<body>
<!--导航栏-->
<div id="3d">
    <header>
        <div class="row model">
            <div class="col-md-3">
                <div style="height: 50px;line-height: 50px;">
                    <a href="/index"><img width="200px" height="50px" src="../imgs/logo2x.png"></a>
                </div>
            </div>

            <div class="col-md-9">
                <div class="row">
                    <div class="col-md-9" style="line-height: 50px">
                        <!--themleaf页面传递参数-->
                        <h1>[[${scene.sName}]]</h1>
                    </div>
                    <div class="col-md-3" style="line-height: 50px">
                        <a href="/login"><img height="30px" src="../imgs/close.png"></a>
                    </div>
                </div>
            </div>
        </div>
    </header>
</div>

</body>
<script>
    //加载场景
    app = new THING.App({
        container	: '3d',
        url			: './scene2',
    });

    app.on('load', function (ev) {
        var floor = app.query('.Building')[0].floors[0];                                    //建筑内楼层
        app.level.change(floor);                                                  //进入建筑层级
        app.pauseEvent(THING.EventType.Click, '*', THING.EventTag.LevelBackMethod);         //暂停单击返回上一层级功能

        app.on(THING.EventType.DBLClick, function(ev) {                                     // 双击右键回到上一层级
            if (ev.button !== 2) {
                return;
            }
            app.level.back();
        }, 'customLevelBackMethod');

        init_toolPanel();                                                                //初始化工具面板
        init_cabinets();                                                                 //初始化机柜


    });
    ////////////侧边工具条及其功能////////////////////////////////////////////////////////////////////////////////////////////
    /**
     * 侧边工具条
     */
    function init_toolPanel(){
        var panel = new THING.widget.Panel({
            //面板位置
            position: [300,1800],
            // 模板样式
            template: "default",
            // 角标样式
            cornerType: "none",
            // 父节点设置，默认为document.body
            parent: document.body,
            // 设置面板宽度
            width: "90",
            // 是否允许有面板title
            hasTitle: false,
            // 设置title图标
            titleImage: "icon.png",
            // title是否允许有关闭按钮
            closeIcon: false,
            // title是否支持拖拽功能
            dragable: false,
            // title是否支持收起功能
            retractable: false,
            // 设置透明度
            opacity: 0.9,
            // 设置层级
            zIndex: 99
        });


        //设置面板中的数据
        var dataObj = {
            space: false,           //空间统计
            monitor: false,         //视频监控
            ring: false,            //动环
            statistics: false,      //承重统计
            assets: false           //资产
        }

        var img0 = panel.addImageBoolean(dataObj, 'space').caption('空间统计').url('../imgs/space.png');
        var img1 = panel.addImageBoolean(dataObj, 'monitor').caption('视频监控').url('../imgs/monitor.png');
        var img2 = panel.addImageBoolean(dataObj, 'ring').caption('动环').url('../imgs/ring.png');
        var img3 = panel.addImageBoolean(dataObj, 'statistics').caption('承重统计').url('../imgs/statistics.png');
        var img4 = panel.addImageBoolean(dataObj, 'assets').caption('资产').url('../imgs/assets.png');

        //给图标绑定事件
        img0.on('change', function(boolValue) {
            onChangeImageButton('space',boolValue);
        });
        img1.on('change', function(boolValue) {onChangeImageButton('monitor',boolValue);});
        img2.on('change', function(boolValue) {onChangeImageButton('ring',boolValue);});
        img3.on('change', function(boolValue) {onChangeImageButton('statistics',boolValue);});
        img4.on('change', function(boolValue) {onChangeImageButton('assets',boolValue);});
    }

    //处理工具条按钮
    function onChangeImageButton(key, boolValue) {
        if(boolValue){
            console.log(boolValue);
            if(key === "space"){
                app.query('服务器').forEach(function (obj) {               //进行空间统计
                    obj.visible = !boolValue;
                    showGraph(obj);
                })
            }
        }else{
            if(key === "space"){                                           //关闭空间统计
                app.query('服务器').forEach(function(obj){
                    obj.visible = true;
                    app.query('.Box').destroyAll();
                });
            }
        }


    }

    //////////////空间统计///////////////////////////////////////////////////////////////////////////////////////////////////
    var GraphColors = ['#0000ff', '#00ffff', '#00ff00', '#ff0000', '#ff00ff', '#ffff00'];

    //创建柱形图
    function  createGraph(obj) {
        if(obj == null){
            return;
        }
        var box = app.create({
            type: 'Box',
            width: obj.size[0] * 0.9,
            height: obj.size[1],
            depth: obj.size[2] * 0.9,
            position: obj.position,
            center: 'Bottom'
        });

        obj.add({
            object: box,
            localPosition: [0, 0, 0]
        });
        box.visible = true;
        box.style.color = Math.randomFromArray(GraphColors);
        box.style.opacity = 0.9;
        box.scale = [1, 0.1, 1];            // 缩放盒子
        box.scaleTo({
            scale: [1, Math.randomFloat(0.2, 4.0), 1],
            time: 400,
            lerpType: THING.LerpType.Linear.Quadratic
        });

    }

    //显示柱形图
    function showGraph(obj) {

        createGraph(obj);

    }

    /////////机柜信息面板///////////////////////////////////////////////////////////////////////////////////////////////////
    //机柜面板相关
    var marker_state = {};
    app.on('load',function () {

        app.query('服务器').forEach(function (obj) {
            obj.on(THING.EventType.MouseEnter, function (ev) {                              //滑入
                obj.style.outlineColor = '#00ff00';                                         //显示描边
                if(marker_state[obj.id] == null || marker_state[obj.id] === undefined){
                    var m =  createMarker(obj, obj.id);
                    marker_state[obj.id] = m;
                    m.visible = true;
                }else{
                    marker_state[obj.id].visible = true;                                     //防止重复创建
                }
            },"tag_in");

            obj.on(THING.EventType.MouseLeave, function (ev) {                                //滑出
                obj.style.outlineColor = null;                                                //描边取消
                marker_state[this.id].visible = false;
            },"tag_out");
        });

    });

    //创建机柜信息面板
    function createMarker(obj, id){
        function createTextCanvas(text) {
            let canvas = document.createElement("canvas");
            const ctx = canvas.getContext("2d");
            ctx.fillStyle = "rgb(29, 255, 0)";                                                 //文字颜色
            ctx.font = "20px sans-serif";
            // ctx.textAlign = "center";
            ctx.textBaseline = "middle";
            ctx.globalAlpha=0.5;
            ctx.fillText(text,30,30);
            return canvas;
        }
        var m = app.create({
            type: "Marker",
            offset: [0, 2, 0],
            size: 3,
            canvas: createTextCanvas('机柜'+id),
            visible:false,
            color:'#ff0000',
            parent: obj
        });
        return m;
    }
    ///////////////播放卡门动画//////////////////////////////////////////////////////////////////////////////////////////////
    // 初始化机柜
    var doorState = null;                                                                       //默认机柜是关闭的
    function init_cabinets() {
        var cabinets = app.query('服务器');
        cabinets.on('dblclick', function () {
            var pos = this.selfToWorld([0, 2.0, 2.1]);                                          // 摄影机飞行
            var targ = this.position;
            targ[1] += 0.95;
            app.camera.flyTo({
                time: 1000,
                position: pos,
                target: targ,
            });

            if (doorState) {                                                                    // 机柜开门动画
                closeDoor(doorState);
                doorState = null;
            }else {
                openDoor(this);
                doorState = this;                                                               // 设置为当前
                this.style.outlineColor = null;                                                 // 当前机柜不沟边
                var state_rackInfo = {};
                app.query('rack').on('click', function () {                                     //给rack创建信息面板
                    if(state_rackInfo[this.id] == null || state_rackInfo[this.id] === undefined){
                        state_rackInfo[this.id] = create_rackUI(this);
                        state_rackInfo[this.id].visible = true;
                    }else{
                        state_rackInfo[this.id].visible = true;                                     //防止重复创建
                    }
                });

            }
        })


        app.on('click', function (event) {                                                      // 右键关门
            if (event.button === 2) {
                if (doorState) {
                    closeDoor(doorState);
                    doorState = null;
                } else {
                    app.camera.flyTo({                                                          // 如果没有当前机柜则飞到一个最佳位置
                        time: 1500,
                        position: [-10.4, 13.6, 12.3],
                        target: [3.6, -4, -1.7],
                    });
                    var floor = app.query('.Building')[0].floors[0];
                    app.level.change(floor);
                }
            }
        });
    }

    //开门
    function openDoor(obj){
        obj.playAnimation('open1');
        createRacks(obj);
    }

    //关门
    function closeDoor(obj) {
        obj.playAnimation({
            name: 'close1',
            complete: function (ev) {
                destroyRacks();
            }
        });
    }

    //////////创建Rack///////////////////////////////////////////////////////////////////////////////////////////////////////
    var RackModels = [
        ['http://model.3dmomoda.cn/models/3817338017ff4776a5dd05f03a3e2fd4/0/gltf', 1],     //rack模型
        ['http://model.3dmomoda.cn/models/37972dd2c96c4a37a3245a00bee3628b/0/gltf', 2]
    ];
    var RACK_UNIT_HEIGHT = 0.0445;                                                          // 1u为4.3厘米
    //创建rack
    function createRacks(obj){
        var curUPos = 0;
        while(true){                                                                        //循环创建rack
            var pair = RackModels[Math.randomInt(0, RackModels.length - 1)];
            var url = pair[0];
            var uHeight = pair[1];
            var rack = createRack(obj,url,curUPos);

            if (curUPos >= Math.randomInt(30,40) - 4)
                break;

            curUPos += uHeight;
        }
        return rack;
    }
    //给每个机箱创建并添加子物体rack
    function createRack(obj,url,curUPos){
        var y = curUPos * RACK_UNIT_HEIGHT;
        var rack = app.create({
            type: 'Rack',
            name: 'rack',
            url: url,
            complete: function() {
                obj.add({
                    object: this,
                    basePoint: 'BasePoint',
                    localPosition: [0, y, 0],
                    localAngles: [0, 0, 0]
                });

            }
        });
        return rack;
    }
    //销毁所有rack
    function destroyRacks() {
        app.query('rack').destroyAll();
    }

    /////////Rack创建并信息面板///////////////////////////////////////////////////////////////////////////////////////////
    //创建rack信息面板
    var state_rackUI = null;
    function create_rackUI(obj) {
        if(state_rackUI === null){
            var ui = new THING.widget.Panel({
                titleText: obj.name,
                closeIcon: true,
                dragable: true,
                retractable: true,
                hasTitle: true,
                width: "300px",
            });
            ui.zIndex = 999999;//设置ui排序
            ui.addTab(rack_info(obj));
            ui.position = [390, 350];
            state_rackUI = ui;
        }else{
            state_rackUI.destroy();                                                     //销毁上一个信息面板
            var ui = new THING.widget.Panel({
                titleText: obj.name,
                closeIcon: true,
                dragable: true,
                retractable: true,
                hasTitle: true,
                width: "300px",
            });
            ui.zIndex = 999999;                                                             //设置ui排序
            ui.addTab(rack_info(obj));
            ui.position = [390, 350];
            state_rackUI = ui;
        }

        return ui;
    }

    //面板信息源
    function rack_info(obj) {
        var type2 = ["PC服务器", "路由器"];
        var type3 = ["DELL", "WINDOWS", "DELL"];
        var people = ["admin_001", "admin_002", "admin_007"];
        var info = {
            "基本信息": {
                "一级分类": "微机",
                "二级分类": type2[Math.randomInt(0,1)],
                "设备类型": type3[Math.randomInt(0,2)],
                "编号": "00" + Math.randomInt(0, 9),
                "使用人": people[Math.randomInt(0,2)],
                "管理员": people[Math.randomInt(0,2)],
                "上架时间": ""+Math.randomInt(10,23)+":"+Math.randomInt(10,23),
            },
            "扩展信息": {
                "信息XX": Math.ceil(Math.random() * 27 + 25) + "",
                "信息YY": Math.ceil(Math.random() * 25 + 20) + "",
                "信息ZZ": Math.ceil(Math.random() * 27 + 25) + "",
                "信息AA": Math.ceil(Math.random() * 25 + 20) + "",
                "信息BB": Math.ceil(Math.random() * 27 + 25) + "",
                "信息CC": Math.ceil(Math.random() * 25 + 20) + "",
                "信息DD": Math.ceil(Math.random() * 25 + 20) + "",
            }
        };
        return info;
    }
</script>

</html>